﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PlaceHR.Processor.Processor.DailyEvent.Steps
{
    class WorkingAgeStepCalculator : StepCalculatorBase<DailyEventProcessorContext, IList<EmployeeAlert>>
    {
        public override void Calculate(DailyEventProcessorContext dailyEventProcessorContext, IList<EmployeeAlert> employeeAlertList)
        {
            DateTime now = DateTime.Now;

            if (dailyEventProcessorContext.CurrentEmployee.DateOfBirth.HasValue)
            {
                int newAge = this.CalcAge(dailyEventProcessorContext.CurrentEmployee.DateOfBirth.Value, now);

                if (newAge > 0 && (!dailyEventProcessorContext.CurrentEmployee.Age.HasValue || newAge > dailyEventProcessorContext.CurrentEmployee.Age.Value))
                {
                    dailyEventProcessorContext.CurrentEmployee.Age = (short)newAge;
                }
            }

            if (dailyEventProcessorContext.CurrentEmployee.StartDate.HasValue)
            {
                int newWorkAge = this.CalcAge(dailyEventProcessorContext.CurrentEmployee.StartDate.Value, now);

                if (newWorkAge > 0 && (!dailyEventProcessorContext.CurrentEmployee.WorkingAge.HasValue || newWorkAge > dailyEventProcessorContext.CurrentEmployee.WorkingAge.Value))
                {
                    dailyEventProcessorContext.CurrentEmployee.WorkingAge = (short)newWorkAge;
                }
            }
        }

        private int CalcAge(DateTime birthDate, DateTime currentDate)
        {
            int age = currentDate.Year - birthDate.Year;

            if (birthDate > currentDate.AddYears(-age))
            {
                age--;
            }
            return age;
        }

    }
}
